package com.zky.gulimall.product.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zky.common.constant.ProductConstant;
import com.zky.common.to.SkuHasStockVo;
import com.zky.common.to.SkuReductionTo;
import com.zky.common.to.SpuBoundTo;
import com.zky.common.to.es.SkuEsModel;
import com.zky.common.utils.R;
import com.zky.gulimall.product.entity.*;
import com.zky.gulimall.product.feign.CouponFeignService;
import com.zky.gulimall.product.feign.SearchFeignService;
import com.zky.gulimall.product.feign.WareFeignService;
import com.zky.gulimall.product.service.*;
import com.zky.gulimall.product.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zky.common.utils.PageUtils;
import com.zky.common.utils.Query;

import com.zky.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService infoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void save(SpuSaveVo spuSaveVo) {
        //1 保存spu基础信息
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(infoEntity);
        //2 保存spu的图片描述
        SpuInfoDescEntity infoDescEntity = new SpuInfoDescEntity();
        infoDescEntity.setSpuId(infoEntity.getId());
        infoDescEntity.setDecript(String.join(",", spuSaveVo.getDecript()));
        infoDescService.saveSpuInfoDesc(infoDescEntity);

        //3保存spu图片集
        List<String> images = spuSaveVo.getImages();
        if (CollectionUtils.isEmpty(images)) {
            throw new RuntimeException("图片不能为空");
        }
        spuImagesService.saveImages(infoEntity.getId(), images);
        //4保存spu的规格参数
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        if (CollectionUtils.isEmpty(baseAttrs)) {
            throw new RuntimeException("spu规则参数信息不能为空");
        }
        List<ProductAttrValueEntity> entityList = baseAttrs.stream().map(e -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();
            valueEntity.setAttrId(e.getAttrId());
            AttrEntity byId = attrService.getById(e.getAttrId());
            if (byId != null) {
                valueEntity.setAttrName(byId.getAttrName());
            }
            valueEntity.setAttrValue(e.getAttrValues());
            valueEntity.setQuickShow(e.getShowDesc());
            valueEntity.setSpuId(infoEntity.getId());
            return valueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(entityList);
        //5 保存spu的积分信息
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(spuSaveVo.getBounds(), spuBoundTo);
        spuBoundTo.setSpuId(infoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (!r.isSuccess()) {
            log.error("couponFeignService saveSpuBounds code:" + r.getCode() + "msg:" + r.getMsg());
            return;
        }
        //5保存当前spu对应的所有sku信息

        //5.1 sku基本信息
        List<Skus> skus = spuSaveVo.getSkus();
        if (CollectionUtils.isEmpty(skus)) {
            throw new RuntimeException("sku信息不能为空");
        }
        skus.forEach(item -> {
            //找默认图片
            String defaultImg = "";
            List<Images> itemImages = item.getImages();
            if (!CollectionUtils.isEmpty(itemImages)) {
                for (Images image : itemImages) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                        break;
                    }
                }
            }

            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            BeanUtils.copyProperties(item, skuInfoEntity);
            skuInfoEntity.setBrandId(infoEntity.getBrandId());
            skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
            skuInfoEntity.setSaleCount(0L);
            skuInfoEntity.setSpuId(infoEntity.getId());
            skuInfoEntity.setSkuDefaultImg(defaultImg);

            skuInfoService.saveSkuInfo(skuInfoEntity);
            //5.2  sku的图片信息
            if (!CollectionUtils.isEmpty(itemImages)) {
                List<SkuImagesEntity> list = itemImages.stream().map(e -> {
                    SkuImagesEntity imagesEntity = new SkuImagesEntity();
                    imagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    imagesEntity.setImgUrl(e.getImgUrl());
                    imagesEntity.setDefaultImg(e.getDefaultImg());
                    return imagesEntity;
                }).filter(f -> !StringUtils.isEmpty(f.getImgUrl())).collect(Collectors.toList());

                skuImagesService.saveBatch(list);
            }

            //5.3 sku的销售属性信息

            List<Attr> attr = item.getAttr();
            if (!CollectionUtils.isEmpty(attr)) {
                List<SkuSaleAttrValueEntity> entities = attr.stream().map(e -> {
                    SkuSaleAttrValueEntity valueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(e, valueEntity);
                    valueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return valueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(entities);
            }

            //5.4 sku的优惠满减信息,符合条件才发送请求
            if (item.getFullCount() > 0 || item.getFullPrice().compareTo(new BigDecimal(0)) == 1) {
                SkuReductionTo reductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, reductionTo);
                reductionTo.setSkuId(skuInfoEntity.getSkuId());
                R reduction = couponFeignService.saveReduction(reductionTo);
                if (!reduction.isSuccess()) {
                    log.error("couponFeignService saveReduction code:" + r.getCode() + "msg:" + r.getMsg());
                    return;
                }
            }
        });

    }

    @Override
    public PageUtils queryPageByContion(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        Object key = params.get("key");
        if (Objects.nonNull(key)) {
            String key1 = (String) key;
            queryWrapper.and(e -> {
                e.eq("id", key1).or().like("spu_name", key1);
            });
        }

        Object status = params.get("status");
        if (Objects.nonNull(status)) {
            String status1 = (String) status;
            queryWrapper.and(e -> {
                e.eq("publish_status", status1);
            });
        }

        Object brandId = params.get("brandId");
        if (Objects.nonNull(brandId)) {
            String brandId1 = (String) brandId;
            if (!brandId1.equals("0")) {
                queryWrapper.and(e -> {
                    e.eq("brand_id", brandId1);
                });
            }
        }

        Object catelogId = params.get("catelogId");
        if (Objects.nonNull(key)) {
            String catelogId1 = (String) catelogId;
            if (!catelogId1.equals("0")) {
                queryWrapper.and(e -> {
                    e.eq("catalog_id", catelogId1);
                });
            }
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        //查出当前spuId对应的所有sku信息，品牌名称
        List<SkuInfoEntity> list = skuInfoService.getSkusBySpuId(spuId);
        List<Long> skuIds = list.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(list)) {
            log.warn("up  getSkusBySpuId return null");
            return;
        }
        List<ProductAttrValueEntity> valueEntities = productAttrValueService.baseAttrListForSpu(spuId);
        List<SkuEsModel.Attrs> attrs = Lists.newArrayList();
        if (!CollectionUtils.isEmpty(valueEntities)) {
            List<Long> attrIdList = valueEntities.stream().map(e -> {
                return e.getAttrId();
            }).collect(Collectors.toList());

            List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIdList);
            if (!CollectionUtils.isEmpty(searchAttrIds)) {
                Set<Long> idSet = new HashSet<>(searchAttrIds);
                attrs = valueEntities.stream().filter(item -> idSet.contains(item.getAttrId())).map(e -> {
                    SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(e, attrs1);
                    return attrs1;
                }).collect(Collectors.toList());
            }
        }

        List<SkuHasStockVo> skuHasStock = wareFeignService.getSkuHasStock(skuIds);
        Map<Long, Boolean> booleanMap = Maps.newHashMap();
        if (!CollectionUtils.isEmpty(skuHasStock)) {
            booleanMap = skuHasStock.stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }
        //封装每个sku信息
        List<SkuEsModel.Attrs> finalAttrs = attrs;
        Map<Long, Boolean> finalBooleanMap = booleanMap;
        List<SkuEsModel> skuEsModels = list.stream().map(item -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(item, esModel);
            esModel.setSkuPrice(item.getPrice());
            esModel.setSkuImg(item.getSkuDefaultImg());
            //todo 查库存
            esModel.setHasStock(finalBooleanMap.get(item.getSkuId()));
            //todo 热度评分
            esModel.setHotScore(0L);
            BrandEntity byId = brandService.getById(item.getBrandId());
            if (byId != null) {
                esModel.setBrandName(byId.getName());
                esModel.setBrandImg(byId.getLogo());
            }

            CategoryEntity entity = categoryService.getById(item.getCatalogId());
            if (entity != null) {
                esModel.setCatalogName(entity.getName());
            }

            esModel.setAttrs(finalAttrs);
            return esModel;
        }).collect(Collectors.toList());

        //保存es
        R productStatusUp = searchFeignService.productStatusUp(skuEsModels);
        //todo 需要考虑接口幂等性问题，会重复上架
        if (!productStatusUp.isSuccess()) {
            log.error("productStatusUp has error,result msg:" + productStatusUp.getMsg());
            return;
        }
        //修改spu状态
        baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());

    }

    @Override
    public SpuInfoEntity spuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        if (byId == null) {
            return null;
        }
        return getById(byId.getSpuId());
    }


    private void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        this.baseMapper.insert(infoEntity);
    }

}